/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package envmailsicep;

import com.entersoft.sicep.log4j.Log4jUtil;
import java.util.List;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import org.hibernate.HibernateException;
import org.hibernate.Query;
/**
 *
 * @author acampos
 */
public class EnvMailFinVencido {
    private static org.apache.log4j.Category logger = Log4jUtil.instance().getCategory(EnvMailDia23.class);
            
    public void EnvMailFinancieroVencido(){
        logger.info("Carga parametro en Clase :  InsArchAntCom" +  "modulo : CargaLista()" );
        org.hibernate.Session session = HibernateUtil.getSessionFactory().openSession();
        try{
            Query query; 
            query = session.getNamedQuery("PRO_SCP_sel_MensajeAlerta_atraso");
            logger.debug(" Sentencia Query["+query.getQueryString()+"]");
            List<ListaEmpSinDoc> lst = query.list();
            if (!lst.isEmpty()){
                for (int j = 0; j < lst.size(); j++){
                    //System.out.println(lst.get(j).getId() + "           " +  lst.get(j).getCorreo());
                    logger.info("Iniciando envio de correos" );
                    if(SendMailAtraso("","cesar.pino@entersoft.cl")){
                        logger.info("Exito envio de correos" );
                        break;
                    }else{
                        logger.error("Error envio de correos" );
                    }
                    logger.info("Finalizando envio de correos" );
                }
            }
        }catch( HibernateException sqle) {
            logger.error("HibernateException: " + sqle.getMessage());
            logger.error("SQLException: " + sqle.getCause().getMessage());
        }catch (Exception j){
            logger.error("[InsArchCtr" + ".init] finally  - Error Exception. "+ j);
        }finally {
            if (session != null) {
                if (session.isConnected()) {
                    session.close();
                }
            }
        }
    }
    
    public boolean SendMailAtraso(String nomEval, String mail){
        boolean retorno = false;
        Properties props  = new Properties();
        props.put("mail.smtp.host", "200.27.173.99");
        props.put("mail.smtp.auth", "true"); 
        String htmlText = "<div align=\"center\"><img src=\"cid:the-img-1\"/></div>"
                    + "<h4 style=\"font-family:Calibri;font-size:14px;font-style:normal\">Estimado Evaluador</h4>"
                    + "<h4 style=\"font-family:Calibri;font-size:14px;font-style:normal\">" + nomEval + "</h4>"
                    + "<div align=\"justify\">"
                    + "<h4 style=\"font-family:Calibri;font-size:13px;font-style:normal\" >Junto con saludar, le informamos que existen Evaluaciones Financieras pendientes de entrega, favor ingresar al sistema para su consulta.</h4>"
                    + "</div>";
                              
               htmlText +="<h4 style=\"font-family:Calibri;font-size:13px;font-style:normal\" >Atte.</h4>";
               htmlText +="<h4 style=\"font-family:Calibri;font-size:13px;font-style:normal\" >Area Mantencion Proveedores</h4>";
               
               
        try {
            SMTPAuthentication auth = new SMTPAuthentication(); 
            Session session = Session.getInstance(props , auth ); 
            MimeMessage message = new MimeMessage(session); 
            //Cuerpo
            BodyPart imgPart=new MimeBodyPart();
 
            // Loading the image
            imgPart.setDataHandler(new DataHandler(getClass().getResource("/util/sicep_mail.png")));
            //Setting the header
            imgPart.setHeader("Content-ID","the-img-1");
            BodyPart texto = new MimeBodyPart();
            texto.setContent(htmlText, "text/html; charset=\"UTF-8\"");
            MimeMultipart multiParte = new MimeMultipart();
            multiParte.addBodyPart(texto);
            multiParte.addBodyPart(imgPart);
            message.setFrom(new InternetAddress("servicioaproveedores@sicep.cl","Gerencia Colaboradores SICEP"));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress (mail));//new InternetAddress ("admininfor@sicep.cl"));
            //message.addRecipient(Message.RecipientType.CC, new InternetAddress ("proveedor@sicep.cl"));
            //message.addRecipient(Message.RecipientType.CC, new InternetAddress ("sicepiquique@sicep.cl"));
            
            message.setSubject("Informes Financieros  Plazo Vencido ");
            message.setContent(multiParte);    
            Transport.send(message);
            retorno = true;
        }catch(MessagingException msg){
            logger.error("MessagingException: " + msg.getMessage());
        } catch (Exception e) {
            logger.error("Exception: " + e.getMessage());
        }
        return retorno;
    }
    
    class SMTPAuthentication extends javax.mail.Authenticator{
        @Override
        public PasswordAuthentication getPasswordAuthentication(){
            String username = "SMTP_User";
            String password = "567.Sicep.";
            return new PasswordAuthentication(username, password);
        }


    }

    class ExceptionManager{

        public void ManageException (Exception e) { 
                logger.error("Exception: " + e.getMessage());
        }
    }  
}
